#!/usr/bin/env  python
#coding=utf-8

import os
import time
import sys
from ftplib import FTP
from  pyinotify import  WatchManager, Notifier, ProcessEvent, IN_DELETE, IIN_CLOSE_WRITE,IN_MOVED_TO,IN_MOVED_FROM

class MonitorFile(ProcessEvent):                                          
    def process_IN_CLOSE_WRITE(self, event):
        file = os.path.join(event.path, event.name)
        ftp_up(file)

#    def process_IN_DELETE(self, event):
#       file = os.path.join(event.path, event.name)
#       ftp_del(file)


#文件上传 
def ftp_up(filename): 
    fullname = filename[5:]
    dir = fullname.split('/')
    if 'p' in dir or 'internals0hu' in dir:
        ftp=FTP() 
        ftp.set_debuglevel(0)      #调试级别2，显示详细信息;0为关闭调试信息 
        ftp.connect('wsfdupload.lxdns.com','21') #连接 
        ftp.login('sohu_ott','sohu_ott!@#2015')  #登录，如果匿名登录则用空串代替即可 
        ftp.cwd('upgrade.ott.sohu.com/%s' % os.path.dirname(fullname)) #选择操作目录 
        bufsize = 1024       #设置缓冲块大小 
        file_handler = open(filename,'rb')  #以读模式在本地打开文件 
        ftp.storbinary('STOR %s' % os.path.basename(fullname),file_handler,bufsize) #上传文件 
        file_handler.close() 
        ftp.quit() 
        print "ftp_up %s in %s done..." %(os.path.basename(fullname),os.path.dirname(fullname))
        os.system('sh /opt/scripts/ftp_monitor/update_finish_txt.sh %s' %dir[2]) #更新文件MD5
        os.system('sh /opt/scripts/ftp_monitor/sendmail.sh %s' %(os.path.basename(fullname))) #发送通知邮件

#本地文件删除后，删除ftp上对应的文件
def ftp_del(filename):
    fullname = filename[5:]
    ftp=FTP()
    ftp.set_debuglevel(0)      #调试级别2，显示详细信息;0为关闭调试信息 
    ftp.connect('wsfdupload.lxdns.com','21') #连接 
    ftp.login('sohu_ott','sohu_ott!@#2015')  #登录，如果匿名登录则用空串代替即可 
    ftp.cwd('upgrade.ott.sohu.com/%s' %os.path.dirname(fullname)) #选择操作目录 
    bufsize = 1024       #设置缓冲块大小 
    ftp.delete('%s' %os.path.basename(fullname))
    ftp.quit()


path = "/data/update/"
wm = WatchManager() 
mask = IN_CREATE|IN_CLOSE_WRITE   #监控新建文件 或者 新创建文件写入完成 
notifier = Notifier(wm, MonitorFile ())
wm.add_watch(path, mask,rec=True)
  

if __name__ == "__main__":
    while True:
        try :
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
        except KeyboardInterrupt:
            notifier.stop()
            break